<template>
  <el-drawer v-model="visible" :show-close="false" class="message-drawer">
    <div class="container flex-column">
      <el-steps :active="activeStep" align-center class="message-step">
        <el-step title="发布通知" @click="activeStep = 1" class="hover" />
        <el-step title="选择学生" />
        <el-step title="发布成功" />
      </el-steps>
      <main class="content">
        <MessageForm
          ref="messageForm"
          :msgType="msgType"
          v-show="activeStep === 1"
        />
        <StudentSelectBox
          ref="studentSelectRef"
          v-if="activeStep === 2"
          v-model:classTypeList="selectList"
          v-model:activeTab="selectType"
          v-model:activeClassList="selectClassList"
          :select-class-info="props.editInfo?.class_info || []"
          :msgType="msgType"
          :subject="messageFormParam.subject"
        />
      </main>
      <footer class="drawer-footer">
        <div class="desc" v-if="activeStep === 2">
          已选：{{
            selectType === MsgReceiverEnum.CLASSROOM
              ? `${selectClassList.length}个班级`
              : `${studentSelectRef?.getCheckedStudentList().length}个学生`
          }}
        </div>
        <div class="btn-cancel" @click="visible = false">取消</div>
        <div class="btn-confirm" @click="onNext" v-if="activeStep === 1">
          下一步
        </div>
        <div class="btn-confirm" @click="onPublish" v-else>发布</div>
      </footer>
    </div>
  </el-drawer>
</template>

<script setup>
import MessageForm from './MessageForm.vue'
import StudentSelectBox from './StudentSelectBox.vue'
import { defineModel, ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { reqPostCreateMsg } from '@/apis/message'
import { MsgReceiverEnum, MsgTypeEnum } from '../constant'

const visible = defineModel('visible')

const props = defineProps({
  // 编辑消息信息
  editInfo: { type: Object },
  msgType: { type: Number, required: true }
})

const emits = defineEmits(['updateMessageList', 'updateMessageDetail'])

const activeStep = ref(1)
const messageForm = ref()
const messageFormParam = ref({})

const studentSelectRef = ref()
const selectList = ref([]) // 班级树状结构
const selectClassList = ref([])
const selectType = ref(MsgReceiverEnum.CLASSROOM) // 1 按人发布, 2 按班发布

const onNext = async () => {
  let formParam = await messageForm.value.getForm()
  if (!formParam) return
  // 班级通知去掉科目
  if (props.msgType === MsgTypeEnum.ClASSROOM) {
    delete formParam.subject
  }
  messageFormParam.value = formParam
  console.log('第一步表单数据 =>', formParam)
  activeStep.value++
}

const onPublish = () => {
  if (
    selectType.value === MsgReceiverEnum.CLASSROOM &&
    selectClassList.value.length === 0
  ) {
    ElMessage.error('请选择班级')
    return
  }
  if (
    selectType.value === MsgReceiverEnum.STUDENTS &&
    !studentSelectRef.value.getCheckedStudentList().length
  ) {
    ElMessage.error('请选择学生')
    return
  }
  sendMessage()
}

// 选择的班级/学生转换成参数结构
const getTaskClassParam = () => {
  function getStudentList(layerList) {
    let studentIds = []
    layerList.forEach(layer => {
      let ids = layer
        .filter(student => student.checked)
        .map(student => student.student_id)
      studentIds.push(...ids)
    })
    return studentIds
  }

  let resList = []
  selectList.value.forEach(typeClass => {
    typeClass.classList.forEach(classItem => {
      if (selectType.value === MsgReceiverEnum.CLASSROOM) {
        if (selectClassList.value.indexOf(classItem.value) >= 0) {
          resList.push({
            class_id: classItem.value,
            class_name: classItem.label,
            class_type: classItem.class_type,
            student_ids: []
          })
        }
      } else {
        let student_ids = getStudentList(classItem.layerList)
        if (student_ids.length) {
          let resItem = {
            class_id: classItem.value,
            class_name: classItem.label,
            class_type: classItem.class_type,
            student_ids
          }
          resList.push(resItem)
        }
      }
    })
  })
  return resList
}

const sendMessage = async () => {
  const class_info = getTaskClassParam()
  const target_type = selectType.value
  const params = {
    ...messageFormParam.value,
    class_info,
    target_type
  }
  // 编辑待发布消息请求参数增加 message_id
  if (props.editInfo) {
    params.message_id = props.editInfo.message_id
  }
  console.log('发通知参数 =>', params)
  const res = await reqPostCreateMsg(params)
  if (res) {
    ElMessage.success('发布成功')
    visible.value = false
    // 编辑通知更新通知详情
    if (props.editInfo) {
      emits('updateMessageDetail')
    }
    // 更新通知列表
    emits('updateMessageList')
  }
}

onMounted(() => {
  nextTick(() => {
    console.log('编辑通知 =>', props.editInfo, messageForm.value)
    if (props.editInfo?.message_id) {
      messageForm.value && messageForm.value.initForm(props.editInfo)
    }
  })
})
</script>

<style lang="less" scoped>
.container {
  gap: 10px;
  height: 100%;
  padding: 30px;
  font-size: @size-big;
  overflow-x: hidden;
  .message-step {
    margin: 0 -100px 16px -100px;
    :deep(.el-step) {
      .el-step__title {
        font-size: @size-base;
      }
      .el-step__title.is-process {
        font-weight: normal;
      }
      .el-step__icon {
        width: 34px;
        height: 34px;
        color: @color-brand-regular;
        border: 1.5px solid #cdced1;
        .el-step__icon-inner {
          font-weight: normal;
          font-size: 16px;
          color: #cdced1;
        }
      }
      .is-finish {
        .el-step__icon {
          color: #fff;
          background-color: @color-brand-regular;
          border-color: @color-brand-regular;
          .el-step__icon-inner {
            color: #fff;
          }
        }
        .el-step__line {
          height: 6px !important;
          border-width: 6px !important;
          background-color: @color-brand-regular;
          border-color: @color-brand-regular;
        }
      }
      .is-process,
      .is-wait {
        color: rgba(4, 11, 26, 0.4);
        .el-step__line {
          height: 6px !important;
          background-color: #f2f4f9;
        }
      }
      .el-step__line {
        width: 70%;
        margin: 0 auto;
        border-radius: 10px;
      }
    }
  }
  .drawer-footer {
    display: flex;
    .desc {
      margin-right: 20px;
      color: #b4b6ba;
    }
    .btn-cancel {
      margin-left: auto;
      margin-right: 12px;
      padding: 4px 20px;
      border-radius: 4px;
      color: @color-brand-regular;
      border: 1px solid @color-brand-regular;
      cursor: pointer;
    }
    .btn-confirm {
      padding: 4px 20px;
      border-radius: 4px;
      color: #fff;
      background-color: @color-brand-regular;
      cursor: pointer;
    }
  }
  .content {
    flex: 1;
    overflow: auto;
  }
}
</style>

<!-- eslint-disable -->
<style lang="less">
.message-drawer {
  width: 620px !important;
  .el-drawer__header {
    margin-bottom: unset !important;
    padding: 0;
  }
  .el-drawer__body {
    padding: 0px;
  }
}
</style>
